package org.nf.web.servlet.param;

import cn.hutool.core.convert.Convert;
import jakarta.servlet.http.Cookie;
import org.nf.web.servlet.MethodArgumentResolver;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.annotation.CookieValue;

import java.lang.reflect.Parameter;

/**
 * @author wangliang
 * @date 2024/6/14
 */
public class CookieMethodArgumentResolver implements MethodArgumentResolver {

    @Override
    public boolean supports(Parameter parameter) {
        return parameter.isAnnotationPresent(CookieValue.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) throws Exception {
        String cookieName = parameter.getAnnotation(CookieValue.class).value();
        Object value = null;
        Cookie[] cookies = servletApi.request().getCookies();
        if(cookies != null) {
            for(Cookie cookie : servletApi.request().getCookies()) {
                if(cookie.getName().equals(cookieName)) {
                    value = Convert.convert(parameter.getType(), cookie.getValue());
                    break;
                }
            }
        }
        return value;
    }
}
